﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Search;
using GUI;
using System.Collections.Generic;
using Groupware;

using Security;

namespace TripLOA.GUI.secure
{
    public partial class Home : TripLOA.GUI.internationalization.LOABasePage
    {
        List<Groupware.Notification> list_notifications;
        List<Groupware.FriendshipRequest> list_friendship_request;
        List<Groupware.FriendshipNotification> list_friendship_notification;
        TripLoaUser user;

        protected void Page_Load(object sender, EventArgs e)
        {
             user = TripLoaUserManager.Instance.getUser(User.Identity.Name);

            list_notifications = Groupware.NotificationManager.getNotifications(user.UserID);
            list_friendship_request = Groupware.NotificationManager.getIncomingFriendshipRequestsByUserID(user);
            list_friendship_notification = Groupware.NotificationManager.getFriendshipNotificationsByUserID(user);


            if (list_friendship_notification!= null && list_friendship_notification.Count > 0)
            {
                there_are_notifications.Visible = true;
                render_friendship_notifications();
                panel_friendship_notifications.Visible = true;
            }

            if (list_friendship_request != null && list_friendship_request.Count > 0)
            {
                there_are_notifications.Visible = true;
                lbl_count_friend_request.Text = list_friendship_request.Count.ToString();
                render_friendship_request_notifications();
                panel1.Visible = true;
                                
            }

            if (list_notifications.Count > 0)
            {
                there_are_notifications.Visible = true;
                count_notifications.Text = list_notifications.Count.ToString();
                render_notifications();
                panel_notications.Visible = true;
            }


            int count_messages = Groupware.MessageManager.GetUserUnreadMessageCount(user);
            if (count_messages > 0)
            {
                count_message.Text = count_messages.ToString();
                panel_messages.Visible = true;
            }

            int numberFeed = Groupware.UserManager.hasPendingFeedbacksToLeft(user.UserID);
            if (numberFeed <= 0)
            {
                hyperFeedback.Visible = false;
            }
            else
            {
                bt_feedback.Visible = true;
                panel_feedback.Visible = true;
                if (Page.Culture == "Italiano (Italia)")
                    hyperFeedback.Text = "Feedback da lasciare: " + numberFeed.ToString();  //TODO: Da cambiare in modo migliore...
                else
                    hyperFeedback.Text = "Feedback to release: " + numberFeed.ToString();

                /*if (User.IsInRole("logged"))
                    Label1.Text = ((RolePrincipal)User).GetRoles()[0];
                RolePrincipal u = ((RolePrincipal) User);*/
            }
        }



        /// <summary>
        /// If you click on a trip notification redirect to tripDetail page, else, if click on user notification redirect
        /// to userProfile page.
        /// </summary>
        protected void SelectNotification(Object sender, GridViewSelectEventArgs e)
        {
            DataKey values = list_link.DataKeys[e.NewSelectedIndex];
            switch (Int32.Parse(values.Values[0].ToString()))
            {
                case Notification.TRIP_CREATED:
                case Notification.TRIP_MODIFIED:
                case Notification.CREATED_TRIP_FOR_EVENT:
                case Notification.CONFIRM_RESERVATION:
                case Notification.DENIED_RESERVATION:
                case Notification.NOTIFY_FELLOWSHIP:
                case Notification.TRIP_DELETED:
                case Notification.PASSENGER_DELETE:
                case Notification.OWNER_DELETE:
                    list_notifications.ElementAt(e.NewSelectedIndex).MarkAsRead();
                    NotificationManager.RemoveAllNotificationsReceivedByUserId(user.UserID, true);
                    Response.Redirect("../passengerTripDetail.aspx?Trip=" + values.Values[1].ToString());
                    break;


                case Notification.FRIEND_REQUEST_ASSOCIATED_TRIP:
                    list_notifications.ElementAt(e.NewSelectedIndex).MarkAsRead();
                    NotificationManager.RemoveAllNotificationsReceivedByUserId(user.UserID, true);
                    string userName = Storage.StorageManager.Instance.GetUserById(Int32.Parse(values.Values[2].ToString())).Username;
                    Response.Redirect("userProfile.aspx?Nick=" + userName);
                    break;

                case Notification.RESERVATION_REQ:
                    /* 
                       cancellazione della notifica fatta al momento della Refuse() o della ConfirmReservation()
                       vedere acceptPassenger.aspx.cs e tripDetail.aspx.cs
                       list_notifications.ElementAt(e.NewSelectedIndex).MarkAsRead();
                       NotificationManager.RemoveAllNotificationsReceivedByUserId(user.UserID, true);
                    */
                    Response.Redirect("tripDetail.aspx?id=" + values.Values[1].ToString());
                    break;
            }
        }
        
        
        protected string getUserName(string id)
        {
            return Storage.StorageManager.Instance.GetUserById(Int32.Parse(id)).Username;
        }

        protected string getFieldValue(string id)
        {
            string fields = "";
            
            for (int i = 0; i < list_notifications.Count(); i++)
            {
                if (list_notifications.ElementAt(i).Id == Int32.Parse(id))
                {
                    if (list_notifications.ElementAt(i).SenderID != null)
                        fields += "From: " + getUserName(list_notifications.ElementAt(i).SenderID.ToString()) + "<br/>";
                    
                    if (list_notifications.ElementAt(i).TripId != null)
                    {
                        Groupware.Trip trip = Groupware.TripManager.GetTripById(list_notifications.ElementAt(i).TripId.Value);
                        fields += "Departure: " + trip.Departure + "<br/>" +
                                  "Arrival: " + trip.Arrival + "<br/>";

                    }
                    
                    /*IDictionaryEnumerator fields_list = list_notifications.ElementAt(i).Fields.GetEnumerator();
                    while (fields_list.MoveNext())
                        fields += "<br/>" + fields_list.Key.ToString() + ": " + fields_list.Value.ToString();
                    */
                    
                }
              
            }
            return fields;
        }


        /// <summary>
        /// Manage the acceptance or not of a friendship request.
        /// </summary>
        protected void AcceptOrDenyFriend(Object sender, GridViewCommandEventArgs e)
        {
            if(e.CommandName == "Accept")
                list_friendship_request.ElementAt(Convert.ToInt32(e.CommandArgument)).AcceptFriendship(user);
            else
                list_friendship_request.ElementAt(Convert.ToInt32(e.CommandArgument)).DenyFriendship(user);

            //panel_friendship_notifications.Load();
            Response.Redirect("Home.aspx");
        }


        /// <summary>
        /// Redirect to the userProfile page of the user that has send friendship request.
        /// </summary>
        protected void VisitNewFriend(Object sender, GridViewCommandEventArgs e)
        {
            int userId = list_friendship_notification.ElementAt(Convert.ToInt32(e.CommandArgument)).NewFriendID;
            list_friendship_notification.ElementAt(Convert.ToInt32(e.CommandArgument)).Delete(user);
            Response.Redirect("~/secure/userProfile.aspx?Nick=" + getUserName(userId.ToString()));
            
        }


        /// <summary>
        /// Show the notifications list on the gridview.
        /// </summary>
        protected void render_notifications()
        {       
              list_link.DataSource = list_notifications;
              list_link.DataBind();
              
        }

        /// <summary>
        /// Show the frienship request notifications list on the gridview.
        /// </summary>
        protected void render_friendship_request_notifications()
        {
            gv_friend_request.DataSource = list_friendship_request;
            gv_friend_request.DataBind();
        }

        /// <summary>
        /// Show the frienship notifications list on the gridview.
        /// </summary>
        protected void render_friendship_notifications()
        {
            gv_friendship_notifications.DataSource = list_friendship_notification;
            gv_friendship_notifications.DataBind();
        }

        /// <summary>
        /// Return a sting that rapresent the notification type.
        /// </summary>
        protected string getNotificationType(string template_type)
        {
            switch (Int32.Parse(template_type))
            {
                case Notification.TRIP_DELETED:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Viaggio Cancellato";
                    else 
                        return "Trip Deleted";

                case Notification.CONFIRM_RESERVATION:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Conferma Prenotazione";
                    else
                        return "Confirm Reservation";

                case Notification.DENIED_RESERVATION:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Prenotazione Negata";
                    else
                        return "Denied Reservation";

                case Notification.RESERVATION_REQ:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Richiesta di Prenotazione";
                    else
                        return "Reservation Request";

                case Notification.NOTIFY_FELLOWSHIP:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Nuovo compagno di viaggio";
                    else
                        return "New Trip's fellow";

                case Notification.EVENT_MODIFIED:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Evento modificato";
                    else
                        return "Event Modified";

                case Notification.EVENT_DELETED:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Evento cancellato";
                    else
                        return "Event Deleted";

                case Notification.CREATED_TRIP_FOR_EVENT:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Nuovo viaggio per evento creato!!";
                    else
                        return "A new trip for event is created!!";

                case Notification.FRIEND_REQUEST_ASSOCIATED_TRIP:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Un tuo amico chiede di associarsi ad un tuo viaggio";
                    else
                        return "Reservation request from your friend";

                case Notification.PASSENGER_DELETE:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Un tuo passeggero è stato cancellato";
                    else
                        return "Passenger is deleted";

                case Notification.OWNER_DELETE:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Il creatore di un viaggio è stato cancellato ";
                    else
                        return "Travel's owner is deleted";

                case Notification.TRIP_CREATED:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Nuovo viaggio!!!";
                    else
                        return "New Trip is created!!!";

                case Notification.TRIP_MODIFIED:
                    if (Page.Culture == "Italiano (Italia)")
                        return "Viaggio modificato";
                    else
                        return "Trip Modified";

                default:
                    return "";
            }
        }

    }
}